//
//  SMGlobalMethod.m
//  Smios
//
//  Created by hao on 15/11/27.
//  Copyright (c) 2015年 sanmi. All rights reserved.
//

#import "SMGlobalMethod.h"
#import <UIKit/UIKit.h>
#import "SDImageCache.h"
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>

#import "GXBaseNavController.h"
#import <AVFoundation/AVFoundation.h>

//#import "MJPhotoBrowser.h"

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

@implementation SMGlobalMethod

const Byte iv[] = {1,2,3,4,5,6,7,8};
//时间戳转时间
+(NSString *)getTimeFromTimeSp:(NSString *)timeSp{
    
    if (timeSp.length <= 0) {
        return @"";
    }
    NSTimeInterval _interval=[timeSp doubleValue];
    if (timeSp.length >= 13) {
        _interval = [timeSp doubleValue] / 1000;
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];

    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyy-MM-dd HH:mm"];
    

    NSString * timeStampString = [objDateformat stringFromDate: date];
 
    return timeStampString;
    
}

//时间戳转时间yyyy-MM-dd
+(NSString *)getTimeFromShortTimeSp:(NSString *)shortTimeSp{
    
    NSTimeInterval _interval = [shortTimeSp doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"YYYY年MM月dd日"];
    NSString * timeStampString = [objDateformat stringFromDate: date];
 
    return timeStampString;
    
}
//时间戳转时间yyyyMMdd
+(NSString *)getTimeFromShortTimeSpY:(NSString *)shortTimeSp{
    
    NSTimeInterval _interval = [shortTimeSp doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyyMMdd"];
    NSString * timeStampString = [objDateformat stringFromDate: date];
    //    DLog(@"%@", timeStampString);
    return timeStampString;
    
}
//13位的时间戳转换
+(NSString *)getTimeFrom13TimeSp:(NSString *)timeSp{
    
    NSString * timeStampString = @"1423189125873";
    NSTimeInterval _interval = [timeStampString doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSLog(@"%@", [objDateformat stringFromDate: date]);
    NSLog(@"date1:%@",date);
    return timeSp;
    
}
//date转时间
+(NSString *)getTimeFromTimeDa:(NSDate *)date{
    
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString * timeStampString = [objDateformat stringFromDate: date];
    return timeStampString;
    
}

//当前时间
+(NSString *)getcurrenTime{
    
    NSDate *date=[NSDate date];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//设置想要的格式
    
    NSString * currentime = [objDateformat stringFromDate: date];
    
    return currentime;

    
}

//当天 最晚时间  XXXX-XX-XX xx:xx  -->  -XXXX-XX-XX 23:59
+(NSString *)gettomorrowTime:(NSString *)startTime{
    
    NSArray *timeArray=[startTime componentsSeparatedByString:@" "];
    
    NSString *time1=timeArray[0];
    
    NSString *time=[NSString stringWithFormat:@"%@ 23:59",time1];
  
    return time;

    
}


//date转时间yyyyMMddHHmm
+(NSString *)getTimeFromTimeDaYY:(NSDate *)date{
    
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyyMMddHHmm"];
    NSString * timeStampString = [objDateformat stringFromDate: date];
    return timeStampString;
    
}

//date转时间yyyyMMddHHmm
+(NSString *)getTimeFromTimeDaY:(NSDate *)date{
    
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyyMMdd"];
    NSString * timeStampString = [objDateformat stringFromDate: date];
    return timeStampString;
    
}


//date转时间
+(NSString *)getTimeFromShortTimeDa:(NSDate *)date{
    
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyy-MM-dd"];
    NSString * timeStampString = [objDateformat stringFromDate: date];
    return timeStampString;
    
}

//时间文本转date(YYYYMMddHHmm)
+ (NSDate *)getTimeDateFromeTimeStrWithYYY:(NSString *)timeStr{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //[formatter setDateStyle:NSDateFormatterMediumStyle];
    //[formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:timeStr]; //------------将字符串按formatter转成nsdate
   
    
    return date;
    
}

//时间文本转date
+(NSDate *)getTimeDateFromeTimeStr:(NSString *)timeStr{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:timeStr]; //------------将字符串按formatter转成nsdate
    return date;
    
}



//时间文本转dateShort
+(NSDate *)getTimeDateFromeShortTimeStr:(NSString *)timeStr{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:timeStr]; //------------将字符串按formatter转成nsdate
    return date;
    
}
//时间文本转dateShort
+(NSDate *)getTimeDateFromeShortTimeStryy:(NSString *)timeStr{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYYMMdd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:timeStr]; //------------将字符串按formatter转成nsdate
    return date;
}
+(NSString *)getTimeSpFromeTimeDate:(NSDate *)date{
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    NSLog(@"timeSp:%@",timeSp); //时间戳的值
    return timeSp;
    
}
//获取当前时间戳
+(NSString *)getTimeSp{
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
    
}

//yyyy-mm-dd转化为yyyy年mm月dd日
+(NSString *)dateFormatter:(NSString*)strDate{
    
    NSString *strSrcDate=strDate;
    NSTimeZone *timeZone=[NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSDateFormatter *fmt=[[NSDateFormatter alloc]init];
    fmt.dateFormat = @"yyyy-MM-dd";
    fmt.timeZone = timeZone;
    NSDateFormatter *dstFmt=[[NSDateFormatter alloc]init];
    dstFmt.dateFormat = @"yyyy年M月d日";
    dstFmt.timeZone = timeZone;
    NSDate *srcDate=[fmt dateFromString:strSrcDate];
    return [dstFmt stringFromDate:srcDate];
}
//日期的比较
+(int)compareDate:(NSString*)startdate withDate:(NSString*)enddate AndFomatterType:(NSString *)fomatterType{
    
    int compare;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:fomatterType];
    NSDate *currentDt = [[NSDate alloc] init];
    NSDate *getDt = [[NSDate alloc] init];
    currentDt = [df dateFromString:startdate];
    getDt = [df dateFromString:enddate];
    NSComparisonResult result = [currentDt compare:getDt];
    switch (result)
    {
        case NSOrderedAscending: //enddate比startdate大
            compare = 1;
            break;
            
        case NSOrderedDescending://enddate比startdate小
            compare = -1;
            break;
            
        case NSOrderedSame://enddate==startdate
            compare = 0;
            break;
            
        default:
            break;
    }
    return compare;
    
}

//自动消失的提示框
+(void)showMessage:(NSString *)message{
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
//    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
//    设置段落模式 ios7的代替方法
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSLineBreakByWordWrapping;
        NSDictionary *attribute = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:15], NSParagraphStyleAttributeName:paragraph};
        CGSize LabelSize = [message boundingRectWithSize:CGSizeMake(290, 9000) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.numberOfLines=0;

    [showview addSubview:label];
    showview.frame = CGRectMake((SCREEN_WIDTH - LabelSize.width - 20)/2, (SCREEN_HEIGHT-LabelSize.height-10)/2, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:3.0f animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
    
}
+ (void)showViewCenterWithMessage:(NSString *)message{
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
   
    if([message isKindOfClass:[NSNull class]]){
        message=@"";
    }
    CGSize labelSize=[message boundingRectWithSize:CGSizeMake(290,9000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:15]} context:nil].size;//根据字体大小 确定 文本size  返回 CGSize
    
    label.frame = CGRectMake(10, 5, labelSize.width, labelSize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.numberOfLines=0;
    
    [showview addSubview:label];
    showview.frame = CGRectMake((SCREEN_WIDTH - labelSize.width - 20)/2, SCREEN_HEIGHT - 100,labelSize.width+20, labelSize.height+10);
    showview.center = window.center;
  
    
    [UIView animateWithDuration:3.0f animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
    
}

//获取系统当前日期和时间（24小时制）
+(NSString *)getTimeWithTwentyFourStyle{
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //将HH换成hh就是12小时制
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return dateString;
    
}

//获取当前 月 周 日 时间
+(NSString *)getWeekTimeWithdate:(NSDate *)currenDate{
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute ;
    
    comps = [calendar components:unitFlags fromDate:currenDate];
    
    
    NSString *week;
    
    switch ([comps weekday]) {
        case 1:
            week=@"周日";
            
            break;
        case 2:
            week=@"周一";
            
            break;
        case 3:
            week=@"周二";
            
            break;
        case 4:
            week=@"周三";
            
            break;
        case 5:
            week=@"周四";
            
            break;
        case 6:
            week=@"周五";
            
            break;
        case 7:
            week=@"周六";
            
            break;
            
        default:
            break;
    }
    
    NSString *stateStr;
    
    if([comps hour]>12){
        
        stateStr=@"下午";
        
    }else{
        
        stateStr=@"上午";
    }
    
    NSString *time=[NSString stringWithFormat:@"%zd月%zd号(%@)  %@%.2zd:%.2zd",[comps month],[comps day],week,stateStr,[comps hour],[comps minute]];
    
    
    
    return time;
    

    
    
}

#pragma mark-- 正则判断
//邮箱
+ (BOOL) validateEmail:(NSString *)email{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
    
}

//手机号码验证
+ (BOOL) validateMobile:(NSString *)mobile{
    
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
    
}
//电话号验证
+ (BOOL)validateIsMobileNumber:(NSString *)mobileNum{
    
    NSString * MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    NSPredicate *regextestPHS = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES)
        || ([regextestPHS evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}

//车牌号验证
+ (BOOL) validateCarNo:(NSString *)carNo{
    
    NSString *carRegex =@"^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$";

    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    
    return [carTest evaluateWithObject:carNo];
    
}

//车型
+ (BOOL) validateCarType:(NSString *)CarType{
    
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
    
}

//用户名
+ (BOOL) validateUserName:(NSString *)name{
    
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
    
}

//密码,这个返回值很诡异，返回yes是包含非法字符。
//+ (BOOL) validatePassword:(NSString *)passWord
//{
//    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
//    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
//    return [passWordPredicate evaluateWithObject:passWord];
//}

//昵称
+ (BOOL) validateNickname:(NSString *)nickname{
    
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
    
}
//账户
+(BOOL)validateAccount:(NSString*)account{
    
    NSString*accountRegex = @"^[\u4e00-\u9fa5a-zA-Z0-9-_]{3,15}";
    NSPredicate*accountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",accountRegex];
    return [accountTest evaluateWithObject:account];
    
}
//密码
+ (BOOL) validatePassword:(NSString *)passWord{
    
    NSString *passWordRegex = @"^[\\p{Punct}a-zA-Z0-9]{6,20}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
    
}
//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard{
    
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    
    return [identityCardPredicate evaluateWithObject:identityCard];
    
}

//邮编
+(BOOL)validateZipcode:(NSString *)zipcode{
    
    //[1-9]\d{5}(?!\d)
    NSString *zipcodeRegex = @"^[1-9]\\d{5}(?!\\d)";
    NSPredicate *zipcodeTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",zipcodeRegex];
    return [zipcodeTest evaluateWithObject:zipcode];
    
}
//验证银行卡
+(NSString *)returnBankName:(NSString*) idCard{
    
   
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"bank" ofType:@"plist"];
    NSDictionary* resultDic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    NSArray *bankBin = resultDic.allKeys;
    
    //6位Bin号
    NSString* cardbin_6 = [idCard substringWithRange:NSMakeRange(0, 6)];
    //8位Bin号
    NSString* cardbin_8 = [idCard substringWithRange:NSMakeRange(0, 8)];
    
    if ([bankBin containsObject:cardbin_6]) {
        
        NSString *bankName_All=[resultDic objectForKey:cardbin_6];
        
        NSString *bankName=[bankName_All componentsSeparatedByString:@"·"][0];
        
        return bankName;
        
    }else if ([bankBin containsObject:cardbin_8]){
        
        NSString *bankName_All=[resultDic objectForKey:cardbin_6];
        
        NSString *bankName=[bankName_All componentsSeparatedByString:@"."][0];
        
        return bankName;
        
    }

    return @"";
        
    

}

#pragma mark- 各类型数据转换
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
        
    }
    return dic;
    
}
//data转字典
+(NSDictionary*)returnDictionaryWithDataPath:(NSData*)data{
    
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
        
    }
    return dic;
    
}
//字典转data
+(NSData*)returnDataWithDictionary:(NSDictionary*)dict{
    
    NSMutableData* data = [[NSMutableData alloc]init];
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:dict forKey:@"talkData"];
    [archiver finishEncoding];
    return data;
    
}
//字典转json串
+(NSString*)returnDictionaryToJson:(NSDictionary *)dic{
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
//数组转data

#pragma mark-- 清理缓存
/*
 清除缓存
 */
//计算单个文件大小
+(float)fileSizeAtPath:(NSString *)path{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
    
}

#pragma mark 压缩图片
+(UIImage*)imageWithImage:(UIImage*)image{
    
    CGFloat scal=image.size.height/image.size.width;
    
    CGSize newSize=CGSizeMake(1000, 1000*scal);
    UIGraphicsBeginImageContext(newSize);
    
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    return newImage;
    
}

//保存图片
+(void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.8);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

+(UIImage *)getImageFromDocumentwithFile:(NSString *)file{
    
    NSString *aPath=[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),file];
    // 拿到沙盒路径图片
    UIImage *imgFromUrl=[[UIImage alloc]initWithContentsOfFile:aPath];
    // 图片保存相册
    //    UIImageWriteToSavedPhotosAlbum(imgFromUrl3, self, nil, nil);
    
    return imgFromUrl;
    
    
}

+(BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

//  获取手机ip 地址
+(NSString *)getDeviceIPIpAddresses

{
    
    int sockfd =socket(AF_INET,SOCK_DGRAM, 0);
    
    //    if (sockfd <</span> 0) return nil;
    
    NSMutableArray *ips = [NSMutableArray array];
    
    
    
    int BUFFERSIZE =4096;
    
    struct ifconf ifc;
    
    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    
    struct ifreq *ifr, ifrcopy;
    
    ifc.ifc_len = BUFFERSIZE;
    
    ifc.ifc_buf = buffer;
    
    if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){
        
        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
            
            ifr = (struct ifreq *)ptr;
            
            int len =sizeof(struct sockaddr);
            
            if (ifr->ifr_addr.sa_len > len) {
                
                len = ifr->ifr_addr.sa_len;
                
            }
            
            ptr += sizeof(ifr->ifr_name) + len;
            
            if (ifr->ifr_addr.sa_family !=AF_INET) continue;
            
            if ((cptr = (char *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;
            
            if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;
            
            memcpy(lastname, ifr->ifr_name,IFNAMSIZ);
            
            ifrcopy = *ifr;
            
            ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);
            
            if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;
            
            
            
            NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
            
            [ips addObject:ip];
            
        }
        
    }
    
    close(sockfd);
    
    
    
    
    
    NSString *deviceIP =@"";
    
    for (int i=0; i < ips.count; i++)
        
    {
        
        if (ips.count >0)
            
        {
            
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
            
            
            
        }
        
    }
    
    return deviceIP;
    
}



#pragma 本地用户数据
//根据key值 读写信息
+(void)writeMessageWithDataDic:(id)message AndKey:(NSString *)key{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user setObject:message forKey:key];
}
+(id)readMessageKey:(NSString *)key{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    return [user objectForKey:key];
}

+(void)removeMessageWithKey:(NSString *)key{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user removeObjectForKey:key];
}
//存储用户登录资料
+(void)writeUserMessageWithUserDic:(id)content{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user setObject:content forKey:@"user"];
    
}
//读取用户信息
+(id)readUserMessage{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    return [user objectForKey:@"user"];
}


//删除登录信息
+(void)removeUserMessage{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user removeObjectForKey:@"user"];
    
}
+(void)savaLoginstatusWithStatus:(BOOL)status{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user setBool:status forKey:@"loginStatus"];
    
}

+(BOOL)readLoginstatus{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    return [user boolForKey:@"loginStatus"];
}


//拨打电话
+(void)telephoneForAppWithNum:(NSString *)telephone{
    
    if(telephone.length==0){
        
        return;
    }
    
    if(CurrenVersion>=10.0){//系统版本大于 10.0
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",telephone]] options:@{} completionHandler:nil];
       
    }else{
        
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",telephone];
        IMYWebView * callWebview = [[IMYWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        
        [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
        
    }
    
}
//取消图片渲染
+(UIImage *)cancelRenderingMode:(UIImage *)image{
    
    image=[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    return image;
    
}
//获取当前系统语言
//en:英文  zh-Hans:简体中文   zh-Hant:繁体中文    ja:日本
+ (NSString*)getPreferredLanguage {
    
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString* preferredLang = [languages objectAtIndex:0];
    NSLog(@"Preferred Language:%@", preferredLang);
    
    return preferredLang;
}
//设置富文本
+(NSMutableAttributedString *)atrbutestringWithcontentStr:(NSString *)contentString Andrange:(NSRange)range Andcolor:(UIColor *)atrbuteColor Andfont:(UIFont *)atrbuteFont{
    
    NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:contentString];
    
    [mstr addAttribute:NSForegroundColorAttributeName value:atrbuteColor range:range];
    [mstr addAttribute:NSFontAttributeName value:atrbuteFont range:range];

    return mstr;
}



+(UIViewController *)getCurrentVC
{
    UIWindow *keyWindow  = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController)
    {
        vc = vc.presentedViewController;
        
        if ([vc isKindOfClass:[UINavigationController class]])
        {
            vc = [(UINavigationController *)vc visibleViewController];
        }
        else if ([vc isKindOfClass:[UITabBarController class]])
        {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}

//获取视频第一帧图片
+(NSData *)getVideoPreViewImage:(NSString *)filePath
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:filePath] options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    NSData *imgData=UIImageJPEGRepresentation(videoImage, 0.7);
    
    return imgData;
}


//**查看大图**//
+(void)showPhotosWithImgUrls:(NSArray *)urls AndselectIndex:(NSInteger)index{
    
//    NSMutableArray *photos = [NSMutableArray array];
//    for (NSString * url in urls) {
//        MJPhoto *photo = [[MJPhoto alloc] init];
//        photo.url = [NSURL URLWithString:url]; // 图片路径
//        [photos addObject:photo];
//    }
//    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
//    browser.currentPhotoIndex = index;
//    browser.photos = photos;
//    [browser show];
    
}

+(void)timeCuterWithSuper:(UIButton *)codeBtn AndoverBlock:(void (^)(void))runLoperBlock{

    __block int timeout=120;
    //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);// 每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                runLoperBlock();
            });
            
        }else{
            
            
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 设置界面的按钮显示 根据自己需求设置
                [codeBtn setTitle:[NSString stringWithFormat:@"重试(%@s)",strTime] forState:UIControlStateNormal];
                
            });
            
            timeout--;
            
        }
        
    });
    
    dispatch_resume(_timer);
    
}
+(CGFloat)heightWithWebView:(IMYWebView *)webView{
    return [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] floatValue];
}

+(NSString*)handleNullString:(id)m_result{
    if(m_result==nil){
        return @"";
    }
    if([m_result isEqual:[NSNull null]]){
        return @"";
    }
    return [NSString stringWithFormat:@"%@",m_result];
}

+(void)prensentViewLoginControllerWithsuccessBlcok:(void (^)(void))successBlock{
    LoginViewController *loginVC=[[LoginViewController alloc]init];
    GXBaseNavController *nava=[[GXBaseNavController alloc]initWithRootViewController:loginVC];
    
    loginVC.loginSuccessBlock = ^{
        if(successBlock){
        successBlock();
        }
    };
    nava.modalPresentationStyle = UIModalPresentationFullScreen;
    [[SMGlobalMethod getCurrentVC] presentViewController:nava animated:YES completion:nil];
}




@end
